<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮（新增...） -->
      <template #toolbar>
        <a-button
          v-for="(item, index) in butData"
          :loading="item.btnKey == 'btnPullSoData' ? loading : false"
          :key="index"
          :type="item.type"
          @click="item.do"
          v-auth="item.auth"
        >
          <Icon v-if="item.icon" :icon="item.icon" /> {{ t(item.title) }}
        </a-button>
      </template>

      <!-- 表格插槽 -->
      <template #ccode="{ record }">
        <a @click="handleForm({ id: record.id })">
          {{ record.ccode }}
        </a>
      </template>
    </BasicTable>
    <BasicModal @register="registerOpen" :title="'启用订单提示'" @ok="handleOpen">
      <div style="margin-top: 20px; font-size: 20px">
        <Icon
          icon="simple-line-icons:question"
          style="margin-right: 10px; color: #f39c12; font-size: 30px"
        />
        确认【启用】选中订单吗？
      </div>
    </BasicModal>

    <BasicModal @register="registerStop" :title="'暂停订单提示'" @ok="handleStop">
      <div style="margin-top: 20px; font-size: 20px">
        <Icon
          icon="simple-line-icons:question"
          style="margin-right: 10px; color: #f39c12; font-size: 30px"
        />
        确认【暂停】选中订单吗？
      </div>
    </BasicModal>

    <BasicModal @register="register1" :title="'信订单完成提示'" @ok="handleSubmit1">
      <div style="margin-top: 20px; font-size: 20px">
        <Icon
          icon="simple-line-icons:question"
          style="margin-right: 10px; color: #f39c12; font-size: 30px"
        />
        确认修改订单状态为【已完成】吗？
      </div>
    </BasicModal>

    <Modal @register="register" @success="handleSuccess" />
    <!-- 页签方式编辑 -->
    <InputFormTabs @register="registerDrawer2" @success="handleSuccess" />
    <!--订单紧急状态修改-->
    <OrderStatusModal @register="registerOrderStatusDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsM8OrderOrderList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref, unref } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable, ActionItem } from '/@/components/Table';
  import { listSet, customListData } from '/@/api/test/testData';
  import { extdBillPull, extdBillRef } from '/@/api/extd/bill/extdBill';
  import Modal from './Modal.vue';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputFormTabs from './formTabs.vue';
  import { schemasData, tabConfigData } from '/@/utils/custom';
  import { useModal, BasicModal } from '/@/components/Modal';
  import { orderDelete } from '/@/api/order/order';
  import { btnEnabelOrder, btnUpdateOrderStatus } from '/@/api/m8/order/order';
  import OrderStatusModal from './orderStatusModal.vue';
  import { handleExport } from '/@/utils/export';

  const { t } = useI18n('sys.role');
  const props = defineProps({
    type: { type: String, default: '' },
  });
  let loading = ref(false);
  const [register, { openModal }] = useModal();
  const [registerOpen, { openModal: openOpenModal, closeModal: closeOpenModal }] = useModal();
  const [registerStop, { openModal: openStopModal, closeModal: closeStopModal }] = useModal();
  const [registerOrderStatusDrawer, { openModal: openOrderStatusModal }] = useModal();
  const [register1, { openModal: openModal1, closeModal: closeModal1 }] = useModal();
  const { showMessage } = useMessage();

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 4, md: 6 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    showAdvancedButton: true,
    schemas: [],
  });
  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');
  const actionColumn: BasicColumn = {
    width: 100, //操作按钮宽度
    actions: (record: Recordable) => {
      actionColumnData.value.forEach((item) => {
        if (item.title == '删除') {
          item.popConfirm = {
            title: '是否确认删除数据',
            confirm: handleDelete.bind(this, { id: record.id }),
          };
          item.ifShow = record.orderStatus != 2 ? true : false;
        }
      });
      return actionColumnData.value;
    },
  };
  // const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawer2, { openDrawer: openDrawer2 }] = useDrawer();
  const [registerTable, { reload, getSelectRowKeys, setProps, getSelectRows, getForm }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    formConfig: searchForm.value as FormProps,
    // resiz                                           eHeightOffset: 60,
    // ellipsis:true

    rowSelection: {
      type: 'checkbox',
    },
  });
  onMounted(async () => {
    const res = await listSet({ viewCode: 'M8_order_list' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);
    searchForm.value.schemas?.forEach((item) => {
      item.defaultValue = props[item.field];
    });

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮

    butData.value.forEach((item) => {
      if (
        item.btnKey == 'btnUpdateJzDate' ||
        item.btnKey == 'btnUpdateHfDate' ||
        item.btnKey == 'btnUpdateYgOverDate'
      ) {
        item.do = () => handOpenModal(item.title, item.btnKey);
      } else if (item.btnKey == 'btnUpdateHxOver') {
        item.do = () => handleConfirm(item.title, item.btnKey);
      } else if (item.btnKey == 'btnPullSoData') {
        item.do = () => handlePull({ extdCode: 'KIS', code: 'SO' });
      } else if (item.btnKey == 'btnOrderStatus') {
        auth: 'm8:order:edit';
        item.do = () => handleOrderStatus(item.title);
      } else if (item.btnKey == 'btnStop') {
        auth: 'm8:order:edit';
        item.do = () => handleStopOrder(item.title);
      } else if (item.btnKey == 'btnOpen') {
        auth: 'm8:order:edit';
        item.do = () => handleOpenOrder(item.title);
      } else if (item.btnKey == 'btnExport') {
        item.do = () => btnExport();
      } else if (item.btnKey == 'btnRef') {
        item.do = () => handleRef({ extdCode: 'KIS', code: 'SO' });
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      ...listTabConfig.value,
      api: customListData,
      beforeFetch: (params) => {
        for (const key in params) {
          if (Array.isArray(params[key])) {
            params[key + '_gte'] = params[key][0];
            params[key + '_lte'] = params[key][1];
            delete params[key];
          }
        }
        params.url = listTabConfig.value.api;
        params.type = params.type ? params.type : props.type;
        // params.jfdate = params.jfdate ? params.jfdate.substring(0, 10) : '';
        // params.xtdate = params.xtdate ? params.xtdate.substring(0, 10) : '';
        // console.log(params, '123456'); //查询列表参数信息
        // params['order.id'] = props.data.id;
        return params;
      },
    });

    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  // 刷新表格数据（含表单回调）
  function handleSuccess() {
    reload();
  }

  function handleConfirm(title, btnKey) {
    var Ids = ref('');
    getSelectRows().forEach((item) => {
      Ids.value += item.id + ',';
    });

    if (getSelectRows().length) {
      openModal1(true, { Ids, title, btnKey });
    } else {
      showMessage('请至少选择一行数据！！');
    }
  }

  // 保存“完成订单”按钮的数据
  async function handleSubmit1() {
    var Ids = ref('');
    getSelectRows().forEach((item) => {
      Ids.value += item.id + ',';
    });
    const res = await btnUpdateOrderStatus({ ids: Ids.value, orderStatus: 2 });
    showMessage(res.message);
    setTimeout(closeModal1);
    reload();
  }

  // 暂停订单
  async function handleStop() {
    var Ids = ref('');
    getSelectRows().forEach((item) => {
      Ids.value += item.id + ',';
    });
    const res = await btnEnabelOrder({ selIds: Ids.value, ope: 9 });
    showMessage(res.message);
    setTimeout(closeStopModal);
    reload();
  }
  // 开启订单
  async function handleOpen() {
    var Ids = ref('');
    getSelectRows().forEach((item) => {
      Ids.value += item.id + ',';
    });
    const res = await btnEnabelOrder({ selIds: Ids.value, ope: 1 });
    showMessage(res.message);
    setTimeout(closeOpenModal);
    reload();
  }

  function handleForm(record: Recordable) {
    openDrawer2(true, record);
  }

  /**
   * 同步订单数据
   */
  async function handlePull(record: Recordable) {
    try {
      loading.value = true;
      const res = await extdBillPull(record);
      showMessage(res.message);
      loading.value = false;
      handleSuccess();
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage('同步订单数据失败');
      }
      console.log('error', error);
    } finally {
      loading.value = false;
    }
  }

  /**
   * 刷新订单数据
   */
  async function handleRef(record: Recordable) {
    try {
      loading.value = true;

      if (getSelectRows().length == 1) {
        var Ids = ref('');
        var codes = ref('');
        getSelectRows().forEach((item) => {
          Ids.value += item.id;
          codes.value += item.ccode;
        });
        record.ids = Ids.value;
        record.codes = codes.value;
        const res = await extdBillRef(record);
        showMessage(res.message);
        loading.value = false;
        handleSuccess();
      } else {
        showMessage('请只选择一行数据！！');
      }
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage('刷新订单数据失败');
      }
      console.log('error', error);
    } finally {
      loading.value = false;
    }
  }

  async function handOpenModal(title, btnKey) {
    var Ids = ref('');
    getSelectRows().forEach((item) => {
      Ids.value += item.id + ',';
    });
    if (getSelectRows().length) {
      openModal(true, { Ids, title, btnKey });
    } else {
      showMessage('请至少选择一行数据！！');
    }
  }

  /**
   * 修改订单紧急状态
   */
  function handleOrderStatus(title) {
    var selRows = getSelectRowKeys();
    var selIds = selRows.join(',');
    if (selRows.length >= 1) {
      openOrderStatusModal(true, { selIds, title });
    } else {
      showMessage('请选择至少一条数据！！');
    }
  }
  /**
   * 暂停订单
   */
  function handleStopOrder() {
    var selRows = getSelectRowKeys();
    var selIds = selRows.join(',');
    if (selRows.length >= 1) {
      openStopModal(true, { selIds, title });
    } else {
      showMessage('请选择至少一条数据！！');
    }
  }
  /**
   * 打开订单
   */
  function handleOpenOrder() {
    var selRows = getSelectRowKeys();
    var selIds = selRows.join(',');
    if (selRows.length >= 1) {
      openOpenModal(true, { selIds, title });
    } else {
      showMessage('请选择至少一条数据！！');
    }
  }

  async function handleDelete(record: Recordable) {
    const res = await orderDelete(record);
    showMessage(res.message);
    handleSuccess();
  }

  //导出数据
  function btnExport() {
    var formdata = getForm().getFieldsValue();
    formdata = { ...formdata, ...props };
    handleExport('/m8/order/exportData', formdata);
  }
</script>
<style>
  .jeesite-editable-cell__action {
    display: none;
  }

  .edit-cell-align-center {
    width: 100% !important;
  }
</style>
